import some from 'lodash/some';
import pick from 'lodash/pick';
import normalizeKeys from '../utils/normalizeKeys';
import * as ResponseCodes from './consts/responseCodes';

const SuccessCodes = pick(ResponseCodes, ['SUCCESS']);

/**
 * 自定义response类
 * @class Response
 * @memberOf kryfe-lib.FetchRequest
 * @inner
 */
export default class CustomResponse {
  static isSuccess(responseCode) {
    return some(SuccessCodes, value => value === responseCode);
  }

  static parseHeaders(res) {
    return normalizeKeys(res.headers || { responseCode: ResponseCodes.UNKNOWN_ERROR, responseMessage: '' });
  }

  static parseBody(res) {
    return normalizeKeys(res.body || {});
  }

  static resetStatic(methods) {
    Object.keys(methods).forEach(key => (CustomResponse[key] = methods[key]));
  }

  constructor(res) {
    this.headers = CustomResponse.parseHeaders(res);
    this.body = CustomResponse.parseBody(res);
    this.code = this.headers.responseCode;
    this.message = this.headers.responseMessage;
    this.success = CustomResponse.isSuccess(this.code);
  }
}
